//
//  FXGradientView.swift
//  FXControls
//
//  Created by fanxx on 2022/9/2.
//

import UIKit

open class FXGradientView: FXHitThroughView {
    open var gradientLayer = CAGradientLayer()
    
    open var colors: [UIColor]? {
        didSet { self.gradientLayer.colors = self.colors?.map { $0.cgColor } }
    }
    open var locations: [CGFloat]? {
        didSet { self.gradientLayer.locations = self.locations as? [NSNumber] }
    }
    open var startPoint: CGPoint {
        get { return self.gradientLayer.startPoint }
        set { self.gradientLayer.startPoint = newValue }
    }
    open var endPoint: CGPoint {
        get { return self.gradientLayer.endPoint }
        set { self.gradientLayer.endPoint = newValue }
    }
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        self.load()
    }
    required public init?(coder: NSCoder) {
        super.init(coder: coder)
        self.load()
    }
    open func load() {
        self.backgroundColor = .clear
        gradientLayer.startPoint = CGPoint(x: 0.5, y: 0)
        gradientLayer.endPoint = CGPoint(x: 0.5, y: 1)
        self.layer.addSublayer(self.gradientLayer)
    }
    open override func layoutSubviews() {
        super.layoutSubviews()
        self.gradientLayer.frame = self.bounds
    }
}

#if canImport(UICreate)
import UICreate

extension UCSetting where TargetType: FXGradientView {
    /// 渐变色
    public static func colors(_ colors: UIColor...) -> Self {
        return .init { target in
            target.colors = colors
        }
    }
    /// 位置
    public static func locations(_ locations: [CGFloat]?) -> Self {
        return .init { target in
            target.locations = locations
        }
    }
    /// 开始位置
    public static func start(_ start: CGPoint) -> Self {
        return .init { target in
            target.startPoint = start
        }
    }
    /// 结束位置
    public static func end(_ end: CGPoint) -> Self {
        return .init { target in
            target.endPoint = end
        }
    }
}

#endif
